//
//  WBRefreshController.swift
//  SainMicroblog
//
//  Created by chenxinju on 16/5/11.
//  Copyright © 2016年 chenxinju-a2. All rights reserved.
//

import UIKit

//定义一个枚举
enum WBRefreshControllerType: Int {
    //正常状态
    case Normal = 0
    //释放更新状态
    case pulling = 1
    
    case Loading = 2
}



class WBRefreshController: UIControl {
    //定义一个状态属性来记录 
    var status: WBRefreshControllerType = .Normal {
    
        didSet {
        
            switch status {
            case .Normal: mesageLabel.text = "下拉刷新"
              //让箭头隐藏 
             arrowImageView.hidden = false
            loadingView.hidden = true
            loadingView.stopAnimating() //停止转动
       UIView.animateWithDuration(0.5, animations: { () -> Void in
           //复原
         self.arrowImageView.transform = CGAffineTransformIdentity
        
       })
         
            case .pulling: mesageLabel.text = "释放更新"
           UIView.animateWithDuration(0.3, animations: { () -> Void in
            //让箭头旋转
            self.arrowImageView.transform = CGAffineTransformMakeRotation(CGFloat(M_PI - 0.01))
          })
    
            case .Loading: mesageLabel.text = "加载中....."
              var inset = scrollView!.contentInset
              inset.top = inset.top + self.frame.height
              scrollView?.contentInset = inset
                
             //让控制器去加载数据 通过回调方法实现
              sendActionsForControlEvents(UIControlEvents.ValueChanged)
                //让箭头隐藏 让加载视图转动
                arrowImageView.hidden = true
                loadingView.hidden = false
                loadingView.startAnimating()
                
                
//            default 把所有情况都列举了 default可以不用
            }
        }
      
    }
    
    //点击刷新 是否会走此方法
    func endRefreshing(){
        
        if  status == .Loading {
         var inset = scrollView!.contentInset
            inset.top = inset.top - self.frame.height
             scrollView?.contentInset = inset
        }
       //停止拖拽 恢复正常状态
       status = .Normal
    }
    
    var scrollView: UIScrollView?
    
   override init(frame: CGRect) {
        super.init(frame: frame)
    
       setupUI()
    }

    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    
    //添加监听
    override func willMoveToSuperview(newSuperview: UIView?) {
       super.willRemoveSubview(newSuperview!)
        
        scrollView = newSuperview as? UIScrollView
        
        //添加监听
        scrollView?.addObserver(self, forKeyPath:"contentOffset", options: NSKeyValueObservingOptions.New, context: nil)
        
    }
    
     //值的改变
    override func observeValueForKeyPath(keyPath: String?, ofObject object: AnyObject?, change: [String : AnyObject]?, context: UnsafeMutablePointer<Void>) {
        
        if scrollView!.dragging { //正在拖拽调用
          
          //[正在拖拽]正常状态
          //[拖拽]释放更新状态 
          if  scrollView?.contentOffset.y < -130 && status == .Normal {
            print("释放更新状态")
              status = .pulling
          }else if scrollView?.contentOffset.y > -130 && status == .pulling {
            //print("正常状态")
            status = .Normal
           }
            
            
        }else {
          //print("没有拖拽了")
          //没有拖拽 需要加载数据 
            if scrollView?.contentOffset.y < -130 && status == .pulling {
              //print("加载")
            //加载数据
            status = .Loading
            }
           
        }
        
    }
    
    //添加子控件
   private func setupUI() {
    backgroundColor = UIColor.yellowColor()
    
    var frame = self.frame
    
    frame.size = CGSizeMake(WBUIScreenW, 44)
    //让视图在导航栏内
    frame.origin.y = frame.origin.y - 44
    
    //设置frame赋值
    self.frame = frame
    
    addSubview(arrowImageView)
    addSubview(mesageLabel)
    addSubview(loadingView)
    //箭头
    arrowImageView.snp_makeConstraints { (make) -> Void in
     make.centerX.equalTo(self.snp_centerX).offset(-30)
     make.centerY.equalTo(self.snp_centerY)
    }
    
    
    //显示视图
    mesageLabel.snp_makeConstraints { (make) -> Void in
        make.left.equalTo(arrowImageView.snp_right)
        make.centerY.equalTo(self.snp_centerY)
    }
    //加载转动视图
   loadingView.snp_makeConstraints { (make) -> Void in
      make.center.equalTo(arrowImageView.snp_center)
    }

  }
    //MARK:- 懒加载控件
    //上箭头
  private  lazy var arrowImageView: UIImageView = {
    
     let img = UIImageView()
        
      img.image = UIImage(named: "tableview_pull_refresh")
    
       return img
    }()
    
    //加载显示lable
    private lazy var mesageLabel: UILabel = {
        let mesage = UILabel()
        mesage.text = "下拉刷新"
        mesage.font = UIFont.systemFontOfSize(17)
        mesage.textAlignment = .Center
        mesage.textColor = UIColor.darkGrayColor()
         return mesage
    }()
    
    
    //旋转视图
    lazy var loadingView:UIActivityIndicatorView = UIActivityIndicatorView(activityIndicatorStyle: UIActivityIndicatorViewStyle.Gray)

}
